<template>
	<view class="container">
		<!-- 顶部导航 -->
		<view class="nav-bar">
			<view class="left" @click="goBack">
				<uni-icons type="left" size="20" color="#FFFFFF"></uni-icons>
			</view>
			<text class="title">课堂 2024/12/01</text>
			<view class="right">
				<uni-icons type="more" size="20" color="#FFFFFF"></uni-icons>
				<uni-icons type="videocam" size="20" color="#FFFFFF"></uni-icons>
			</view>
		</view>

		<!-- 共享区域 -->
		<view class="share-area">
			<!-- 图片展示区域 -->
			<scroll-view class="share-content" scroll-y>
				<image :src="currentImage" mode="widthFix"></image>
			</scroll-view>
			<view v-if="showControll">
				<button type="default" size="mini" @click="pre">上一张</button>
				<button type="default" size="mini" @click="next">下一张</button>
			</view>
			<view class="share-info" v-if="showControll">
				<!-- @Change 选择改变时的处理函数 :value当前选中的索引值 :range选择器的数据源 range-key指定显示的属性名 -->
				<picker @change="handleCatalogChange" :value="currentCatalogIndex" :range="catalogList"
					range-key="name">
					<view class="picker-content">
						<text class="file-name">{{ currentCatalogName }}</text>
						<text class="page-info">{{ currentPageInfo }}</text>
						<uni-icons type="bottom" size="14" color="#666"></uni-icons>
					</view>
				</picker>
			</view>
		</view>

		<!-- 活动区域 -->
		<view class="activity-area">
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					{{ tab }}
				</view>
			</view>

			<!-- 课堂活动列表 -->
			<scroll-view scroll-y class="activity-list">

        <!-- 签到活动列表 -->
        <view class="activity-item" v-for="(activity, index) in signInActivities" :key="index"
              v-if="currentTab === 0" @click="showSignInDetail(activity)">
          <view class="activity-header">
            <text class="activity-title">签到</text>
            <text class="activity-status">{{ activity.status }}</text>
          </view>
          <view class="activity-content">
            <text class="sign-in-text">签到时间：{{ formatSignInTime(activity.startTime) }}</text>
            <text class="sign-in-duration">持续时间：{{ activity.endType }}分钟</text>
          </view>
        </view>

				<!-- 抢答活动 -->
				<view class="activity-item" v-if="currentTab === 0" @click="answerAct()">
					<view class="activity-header">
						<text class="activity-title">抢答</text>
						<text class="activity-status">已结束</text>
					</view>
					<view class="activity-content">
						<text class="answer-text">111</text>
						<view class="score">
							<uni-icons type="star" size="16" color="#666"></uni-icons>
							<text>+0</text>
						</view>
					</view>
				</view>

				<!-- 讨论区域 -->
				<template v-if="currentTab === 1">
					<scroll-view class="discussion-area" scroll-y>
						<view class="message-list">
							<view class="message-item" v-for="(msg, index) in messages" :key="index">
								<text class="sender">{{myusername}}:</text>
								<text class="content">{{ msg }}</text>
							</view>
						</view>
					</scroll-view>

					<!-- 发送框区域 -->
					<view class="send-area">
						<input class="message-input" type="text" v-model="messageText" placeholder="请输入内容..." />
						<button class="send-btn" @click="sendMessage">发送</button>
					</view>
				</template>

				<!-- 不懂区域 -->
				<view class="question-area" v-if="currentTab === 2">
					<view class="question-list">
						<!-- 问题列表 -->
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 抢答弹窗 -->
		<view class="answer-popup" v-if="showAnswerPopup">
			<view class="answer-popup-content">
				<view class="answer-title">{{quick.quickName}}</view>
				<view class="answer-buttons">
					<button class="cancel-btn" @click="cancelAnswer">取消</button>
					<button class="enter-btn" @click="enterAnswer">抢答</button>
				</view>
			</view>
		</view>

    <!-- 添加签到弹框 -->
    <uni-popup :ref="el => signInPopupRef = el" type="center" background-color="#fff">
      <view class="sign-in-popup">
        <view class="popup-header">
          <text class="title">课堂签到</text>
        </view>
        <view class="popup-content">
          <view class="sign-code-input">
            <text class="label">请输入签到码：</text>
            <input type="text" v-model="inputSignCode" placeholder="请输入签到码" class="sign-code-field" />
          </view>
          <view class="countdown">
            <text class="label">剩余时间：</text>
            <text class="value">{{ formatRemainingTime }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" type="primary" @click="handleSignIn">确认签到</button>
          <button class="cancel-btn" @click="closeSignInPopup">取消</button>
        </view>
      </view>
    </uni-popup>

    <!-- 添加签到详情弹窗 -->
    <uni-popup ref="signInDetailPopupRef" type="center" background-color="#fff">
      <view class="sign-in-popup">
        <view class="popup-header">
          <text class="title">签到详情</text>
        </view>
        <view class="popup-content">
          <view class="detail-item">
            <text class="label">签到时间：</text>
            <text class="value">{{ formatSignInTime(currentSignInDetail?.startTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">持续时间：</text>
            <text class="value">{{ currentSignInDetail?.endType }}分钟</text>
          </view>
          <view class="detail-item">
            <text class="label">签到状态：</text>
            <text class="value" :class="currentSignInDetail?.status === '已签到' ? 'success' : ''">
              {{ currentSignInDetail?.status }}
            </text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closeSignInDetail">关闭</button>
        </view>
      </view>
    </uni-popup>

	</view>
</template>

<script setup>
	import {onLoad} from '@dcloudio/uni-app'; //yh
	import {
		ref,
		onMounted,
		onUnmounted,
		onBeforeUpdate,
		watch,
		computed,
    nextTick
	} from 'vue';
	
  import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	// 响应式数据
	const tabs = ref(['课堂活动', '讨论', '不懂']);
	const currentTab = ref(0);
	const activities = ref([{
		type: 'answer',
		title: '1111',
		status: '已结束',
		content: '2323223',
		score: 0
	}]);

	const signInPopupRef = ref(null)
	const isFullscreen = ref(false);
	const messageText = ref(''); // 输入框内容
	const messages = ref([]); // 消息列表
	const currentIndex = ref(0); // 当前图片索引
	const images = ref(); // 存储后端返回的图片数据
	const currentCatalogId = ref(null); // 当前显示的目录ID
	const currentCatalogIndex = ref(0); //当前目录的索引

	const myusername = ref('')//发送信息的人的姓名
	const roleId = ref(0)

  // 在响应式数据部分添加签到活动列表
  const signInActivities = ref([]); // 存储签到活动记录
  const inputSignCode = ref(''); // 学生输入的签到码

	//抢答的对象
	const quick = ref({
		quickName:'',
		quickNum:0,
		quickUsername:myusername.value
	})


	const currentImage = computed(() => {
		// 检查必要的数据是否存在
		if (!images.value || !currentCatalogId.value) {
			console.log('数据不存在:', {
				images: !!images.value, //双感叹号将值转换为布尔值（true/false）
				catalogId: currentCatalogId.value, // 直接输出目录ID的值
			});
			return '';
		}

		// 获取当前目录的图片数组
		const currentCatalogImages = images.value[currentCatalogId.value];

		if (!currentCatalogImages || !currentCatalogImages[currentIndex.value]) {
			console.log('图片不存在:', {
				hasImages: !!currentCatalogImages,
				index: currentIndex.value
			});
			return '';
		}

		// 返回当前图片URL
		console.log('加载图片:', currentCatalogImages[currentIndex.value].photoUrl);
		return currentCatalogImages[currentIndex.value].photoUrl;//返回当前需要显示的照片
	});




	//判断是否是老师，进行相关的权限校验
	const props = defineProps({
		isTeacher: {
			type: Boolean,
			default: false
		}
	})
	//修改文件选择和图片切换按钮的显示逻辑
	const showControll = computed(()=> computedIsTeacher) ;

	/**
	 * 将后端返回的数据转换为选择器需要的格式
	 */
	const catalogList = computed(() => {
		//首先检查images数据是否存在
		if (!images.value) return [];
		//2.获取所有的目录id并转换数据
		return Object.keys(images.value).map(id => {
			//3. 获取当前目录的图片数组
			const catalogImages = images.value[id];
			//4.检查当前目录是否有有效数据
			if (!catalogImages || !catalogImages[0]) {
				//5.如果没有数据，返回默认对象
				return {
					id: Number(id), //目录Id转为数字
					name: `目录 ${id}`, //默认目录名
					pageCount: 0 //默认页数为0
				};
			}
			//6.如果有数据，返回实际数据对象
			return {
				id: Number(id),
				name: catalogImages[0].modelName || `目录 ${id}`, //使用文件名，如果没有则使用默认名
				pageCount: catalogImages[0].pageCount || 0 //使用实际页数，如果没有则为0
			};
		});
	});

	// 计算当前目录名称
	const currentCatalogName = computed(() => {
		const catalog = catalogList.value[currentCatalogIndex.value];
		return catalog ? catalog.name : '';
	});

	// 计算当前页码信息
	const currentPageInfo = computed(() => {
		if (!images.value || !currentCatalogId.value) return '';
		const currentCatalogImages = images.value[currentCatalogId.value];
		if (!currentCatalogImages || !currentCatalogImages[0]) return '0/0页';
		return `${currentIndex.value + 1}/${currentCatalogImages[0].pageCount}页`;
	});

	// 处理目录切换
	const handleCatalogChange = (e) => {
		const index = e.detail.value;
		currentCatalogIndex.value = index;
		const newCatalogId = catalogList.value[index].id;
		currentCatalogId.value = newCatalogId;
		currentIndex.value = 0; // 切换目录时重置为第一张

		// 发送目录切换的同步消息
		const message = {
			type: 'CATALOG_SYNC',
			data: {
				catalogId: newCatalogId,
				index: 0 // 切换目录时默认显示第一张
			}
		};
		uni.sendSocketMessage({
			data: JSON.stringify(message)
		});
	};

	// 方法
	const goBack = () => {
		uni.navigateTo({
			url: '/pages/study/course-detail'
		})
	};

	const switchTab = (index) => {
		currentTab.value = index;
	};


	const toggleFullscreen = () => {
		// 切换横屏全屏显示
		if (!isFullscreen.value) {
			plus.screen.lockOrientation('landscape');
			// 进入全屏模式
			const currentWebview = getCurrentPages()[getCurrentPages().length - 1].$getAppWebview();
			currentWebview.setFullscreen(true);
		} else {
			plus.screen.lockOrientation('portrait');
			const currentWebview = getCurrentPages()[getCurrentPages().length - 1].$getAppWebview();
			currentWebview.setFullscreen(false);
		}
		isFullscreen.value = !isFullscreen.value;
	};

	const socket = ref(false);
	const selectedOption = ref('1');
	const courseId = ref(0) ;
	const array = ref([]);

	const classId = ref(0);//yh  classId

	//yh 加入
	// 使用 onLoad 获取页面加载时传递的参数

	onLoad((options) => {
		console.log("options.classId=" + options.classId); // 打印出上个页面传递的 id 参数。接收的是课堂id
		classId.value = options.classId;
	});
	const answerAct = () => {
		console.log("classId=" + classId.value);
		uni.reLaunch({
			url: '/pages/study/app-sing-in?classId=' + classId.value
		});
	}
	//yh 加入结束
	//获取文件资源Id
	const getResourceId = async () =>{
		const res = await uni.request({
			url: 'http://192.168.100.54:8080/classRoom/getClassResourceId',
			method: 'GET',
			data:{
				classroomId: classId.value
			}
		});
		if(res.data!=null){
			array.value = res.data;
			initResource(array.value) ;
		}
	}

	//初始化获取资源
	const initResource = async (arr) => {
		try {
			const res = await uni.request({
				url: 'http://192.168.100.54:8080/classRoom/getClassResource',
				method: 'POST',
				header: {
					'content-type': 'application/json'
				},
				data: arr
			});
			if (res.data.code === 200) {
				images.value = res.data.t;
				console.log('完整的响应数据:', res.data);
				console.log('images值:', images.value);

				// 设置初始状态
				setDefaultState();
			} else {
				console.log('error');
			}
		} catch (error) {
			console.error('获取资源失败:', error);
				uni.showToast({
					title: '获取资源失败',
					icon: 'none'
				});
		}
	};


	const connectWebSocket = () => {
		uni.connectSocket({
			url: "ws://192.168.100.132:8080/channel",
			success: () => {
				console.log('Connect to WebSocket server....');
			},
			fail: (err) => {
				console.log('Failed to connect to WebSocket server:', err);
			}
		});

		//监听打开事件
		uni.onSocketOpen(() => {
			console.log("connect success");
			socket.value = true;
			// WebSocket连接成功后，请求当前状态
			requestCurrentState();
		});

		// 监听接收到的消息
		uni.onSocketMessage((res) => {
			console.log('收到服务器内容：' + res.data);
			try {
				const message = JSON.parse(res.data);

				switch (message.type) {
					case 'IMAGE_SYNC':
					case 'CATALOG_SYNC':
						const { catalogId, index } = message.data;

						if (currentCatalogId.value !== catalogId) {
							currentCatalogId.value = catalogId;
							const newCatalogIndex = catalogList.value.findIndex(cat => cat.id === catalogId);
							if (newCatalogIndex !== -1) {
								currentCatalogIndex.value = newCatalogIndex;
							}
						}
						currentIndex.value = index;
						break;

					case 'CURRENT_STATE':
						if (message.data && message.data.currentCatalogId) {
							const { currentCatalogId: serverCatalogId, currentIndex: serverIndex } = message.data;
							if (currentCatalogId.value !== serverCatalogId) {
								currentCatalogId.value = serverCatalogId;
								const newCatalogIndex = catalogList.value.findIndex(cat => cat.id === serverCatalogId);
								if (newCatalogIndex !== -1) {
									currentCatalogIndex.value = newCatalogIndex;
								}
							}
							currentIndex.value = serverIndex;
						}
						break;

					case 'CHAT_MESSAGE':
						const { info,username } = message.data ;
						myusername.value = username ;
						messages.value.push(info);
						break;

          case 'SIGN_IN_SYNC':
            // 处理签到消息
            handleSignInSync(message.data);
            break;

          case 'STUDENT_SIGN_IN':
            // 处理学生签到状态更新
            if (message.data.userId === currentUserId.value) {
              // 更新活动列表中的签到状态
              const activity = signInActivities.value.find(a => a.id === message.data.signId);
              if (activity) {
                // 直接使用后端返回的状态
                activity.status = message.data.signStatus || '未签到';
              }

              // 显示签到结果
              uni.showToast({
                title: message.data.signStatus === '已签到' ? '签到成功' : '签到失败',
                icon: message.data.signStatus === '已签到' ? 'success' : 'error'
              });
            }
            break;

					case 'QUICK_MESSAGE':
						// 处理抢答消息 弹出抢答页面
						showAnswerPopup.value = true;
						const quick1 = JSON.parse(res.data) ;
						quick.value = quick1.data ;
						quick.value.quickUsername = myusername.value
						break;
					default:
						console.log('未知的消息类型:', message.type);
				}
			} catch (error) {
				console.error('处理收到的消息失败:', error);
			}
		});

		// 监听WebSocket关闭事件
		uni.onSocketClose(() => {
			console.log('WebSocket已关闭！');
			socket.value = false;
		});
	};

	//聊天发送信息的方法
  const sendMessage = () => {
    if (messageText.value.trim()) {  // 检查消息内容是否有效
      const message = {
        type: 'CHAT_MESSAGE',
        data: {
          info: messageText.value,
          username: myusername.value
        }
      }
      uni.sendSocketMessage({
        data: JSON.stringify(message),
        success: () => {
          messageText.value = '';  // 发送成功后清空输入框
        },
        fail: (error) => {
          console.error('息发送失败:', error);
          uni.showToast({
            title: '发送失败',
            icon: 'error'
          });
        }
      });
    } else {
      uni.showToast({
        title: '请输入内容',
        icon: 'none'
      });
    }
  };

	// 图片切换方法
	const pre = () => {
		if (!images.value || !images.value[currentCatalogId.value]) {
			return;
		}
		const currentCatalogImages = images.value[currentCatalogId.value];
		if (currentIndex.value > 0) {
			currentIndex.value--;
		} else {
			uni.showToast({
				title: '已经是第一张',
				icon: 'none'
			});
		}
		console.log('上一张',currentCatalogImages[currentIndex.value].photoUrl);
		sendImageSync(currentCatalogImages[currentIndex.value].photoUrl);
	};

	const next = () => {
		if (!images.value || !images.value[currentCatalogId.value]) {
			return;
		}
		const currentCatalogImages = images.value[currentCatalogId.value];
		if (currentIndex.value < currentCatalogImages.length - 1) {
			currentIndex.value++;
		} else {
			uni.showToast({
				title: '已经是最后一张',
				icon: 'none'
			});
		}
		console.log('下一张',currentCatalogImages[currentIndex.value].photoUrl);
		sendImageSync(currentCatalogImages[currentIndex.value].photoUrl);
	};
	//同步切换图片的方法
	const sendImageSync = (imageUrl) => {
		const message = {
			type: 'IMAGE_SYNC',
			data: {
				imageUrl: imageUrl,
				catalogId: currentCatalogId.value,
				index: currentIndex.value
			}
		};
		uni.sendSocketMessage({
			data: JSON.stringify(message)
		});
	};

	const computedIsTeacher = computed(() => {
	  return roleId.value === 1 ? false : true;
	});
	// 生命周期钩子
	onMounted(async () => {
		// 先获取资源
		getResourceId() ;
		// 然后建立WebSocket连接
		connectWebSocket();
		//获取当前登陆人的姓名
		const userInfo = JSON.parse(uni.getStorageSync('id')) ;
		myusername.value = userInfo[0].username ;
		roleId.value = userInfo[0].roleId ;
    // 获取当前用户ID   获取不到！！！！！！！！！！！！！
    // 写死值    userInfo[0].userId
    currentUserId.value = 1;
    // 添加定时器，每秒更新倒计时
    timerInterval = setInterval(() => {
      if (signInData.value) {
        const now = new Date().getTime();
        const endTime = signInData.value.startTime + (signInData.value.endType * 60 * 1000);
        if (now >= endTime) {
          closeSignInPopup();
          clearInterval(timerInterval);
        }
      }
    }, 1000);
	});

	// 页面卸载时恢复竖屏
	onUnmounted(() => {
		if (isFullscreen.value) {
			plus.screen.lockOrientation('portrait');
			const currentWebview = getCurrentPages()[getCurrentPages().length - 1].$getAppWebview();
			currentWebview.setFullscreen(false);
		}
    // 清除时器
    if (timerInterval) {
      clearInterval(timerInterval);
    }
	});

	// 添加重连相关的变量
	const isConnecting = ref(false);
	const reconnectAttempts = ref(0);
	const maxReconnectAttempts = 5;

	// 添加重连函数
	const reconnectWebSocket = () => {
		if (isConnecting.value || reconnectAttempts.value >= maxReconnectAttempts) return;

		isConnecting.value = true;
		setTimeout(() => {
			reconnectAttempts.value++;
			connectWebSocket();
			isConnecting.value = false;
		}, 3000); // 3秒后重试
	};

	// 在WebSocket关闭时尝试重连
	uni.onSocketClose(() => {
		console.log('WebSocket已关闭！');
		socket.value = false;
		reconnectWebSocket();
	});

	// 添加请求当前状态的方法 尝试重新连接的标志REQUEST_STATE
	const requestCurrentState = () => {
		const message = {
			type: 'REQUEST_STATE'
		};
		uni.sendSocketMessage({
			data: JSON.stringify(message)
		});
	};

	// 添加默认状态设置方法
	const setDefaultState = () => {
		if (images.value) {
			const catalogIds = Object.keys(images.value);
			if (catalogIds.length > 0) {
				currentCatalogId.value = Number(catalogIds[0]);
				currentCatalogIndex.value = 0;
				currentIndex.value = 0;
			}
		}
	};

  // 在 script setup 中添加新的响应式变量
  const showSignInDialog = ref(false); // 控制签到弹框显示
  const signInData = ref(null); // 存储签到数据
  const currentUserId = ref(1); // 当前用户ID
  // 添加签到处理方法
  const handleSignIn = async () => {
    try {
      if (!inputSignCode.value) {
        uni.showToast({
          title: '请输入签到码',
          icon: 'none'
        });
        return;
      }

      if (inputSignCode.value !== signInData.value.signCode) {
        uni.showToast({
          title: '签到码错误',
          icon: 'error'
        });
        return;
      }

      const message = {
        type: 'STUDENT_SIGN_IN',
        data: {
          signId: signInData.value.signId,
          userId: currentUserId.value,
          signCode: inputSignCode.value,
          signStatus: '已签到'  // 发送签到状态
        }
      };

      // 先更新本地状态
      const activity = signInActivities.value.find(a => a.id === signInData.value.signId);
      if (activity) {
        activity.status = '已签到';
      }

      uni.sendSocketMessage({
        data: JSON.stringify(message),
        success: () => {
          console.log('签到请求已发送');
        },
        fail: (error) => {
          // 如果发送失败，恢复状态
          if (activity) {
            activity.status = '未签到';
          }
          console.error('签到请求发送失败:', error);
          uni.showToast({
            title: '签到失败',
            icon: 'error'
          });
        }
      });

      closeSignInPopup();
    } catch (error) {
      console.error('签到失败:', error);
      uni.showToast({
        title: '签到失败',
        icon: 'error'
      });
    }
  };

  // 添加显示和关闭弹框的方法
  const showSignInPopup = () => {
    if (signInPopupRef.value) {
      signInPopupRef.value.open('center');
    } else {
      console.error('popup ref not found');
    }
  };

  // 添加弹框状态变化的处理方法
  const popupChange = (e) => {
    console.log('弹框状态变化：', e);
  };

  // 添加倒计时更新逻辑
  const formatRemainingTime = computed(() => {
    if (!signInData.value) return '0:00';

    const now = new Date().getTime();
    const endTime = signInData.value.startTime + (signInData.value.endType * 60 * 1000);
    const remaining = Math.max(0, endTime - now);

    if (remaining <= 0) {
      // 如果时间到了，自动关闭弹框
      closeSignInPopup();
      return '0:00';
    }

    const minutes = Math.floor(remaining / (60 * 1000));
    const seconds = Math.floor((remaining % (60 * 1000)) / 1000);

    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  });

  // 添加定时器更新倒计时
  let timerInterval = null;

  // 添加处理签到同步的方法
  const handleSignInSync = (data) => {
    console.log('收到签到消息:', data);
    console.log('是否为教师:', props.isTeacher);

    // 添加到活动列表
    const newActivity = {
      id: data.id,
      signCode: data.signCode,
      startTime: new Date().getTime(),
      endType: parseInt(data.signTime),
      status: '未签到',  // 初始状态为未签到
      userId: currentUserId.value  // 添加用户ID
    };
    signInActivities.value.unshift(newActivity);

    if (!props.isTeacher) {
      signInData.value = {
        signId: data.id,
        signCode: data.signCode,
        startTime: new Date().getTime(),
        endType: parseInt(data.signTime)
      };

      inputSignCode.value = '';

      nextTick(() => {
        if (signInPopupRef.value) {
          signInPopupRef.value.open('center');
        } else {
          console.error('签到弹框组件未找到');
        }
      });

      startSignInCountdown();
    }
  };

  // 添加开始倒计时的方法
  const startSignInCountdown = () => {
    if (timerInterval) {
      clearInterval(timerInterval);
    }

    timerInterval = setInterval(() => {
      if (signInData.value) {
        const now = new Date().getTime();
        const endTime = signInData.value.startTime + (signInData.value.endType * 60 * 1000);
        if (now >= endTime) {
          closeSignInPopup();
          clearInterval(timerInterval);

          // 更新活动状态
          const activity = signInActivities.value.find(a => a.id === signInData.value.signId);
          if (activity) {
            activity.status = '已结束';
          }

          uni.showToast({
            title: '签到时间已结束',
            icon: 'none'
          });
        }
      }
    }, 1000);
  };

  // 修改关闭弹框的方法
  const closeSignInPopup = () => {
    if (signInPopupRef.value) {
      signInPopupRef.value.close();
      // 清除签到数据
      signInData.value = null;
      // 清除倒计时
      if (timerInterval) {
        clearInterval(timerInterval);
      }
    }
  };

  // 添加格式化签到时间的方法
  const formatSignInTime = (timestamp) => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  // 添加新的响应式变量
  const signInDetailPopupRef = ref(null);
  const currentSignInDetail = ref(null);

  // 添加显示签到详情的方法
  const showSignInDetail = (activity) => {
    currentSignInDetail.value = activity;
    nextTick(() => {
      if (signInDetailPopupRef.value) {
        signInDetailPopupRef.value.open('center');
      }
    });
  };

  // 关闭签到详情
  const closeSignInDetail = () => {
    if (signInDetailPopupRef.value) {
      signInDetailPopupRef.value.close();
    }
  };
	// 在 script setup 中添加新的响应式变量
	const showAnswerPopup = ref(false); // 控制抢答弹窗显示默认false
	const isQuicked = ref({}) ;
	// 添加进入抢答的方法---------------
	const enterAnswer = async() => {
		showAnswerPopup.value = false;
		const res = await uni.request({
			url: 'http://192.168.100.54:8080/quick/sec',
			method:'POST',
			header:{
				'content-type':'application/json'
			},
			data: JSON.stringify(quick.value)
		});
		uni.navigateTo({
			url:'/pages/study/app-sing-in?isQuicked='+JSON.stringify(res.data.t)
		})

	};


	// 添加取消抢答的方法
	const cancelAnswer = () => {
		showAnswerPopup.value = false;
	};

</script>

<style lang="scss">
.test {
  display: none;
}

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  background-color: #67C23A;
  padding: 40px 20rpx 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #FFFFFF;

  .left,
  .right {
    display: flex;
    align-items: center;
    gap: 20rpx;
  }

  .title {
    font-size: 32rpx;
    font-weight: 500;
  }
}

.share-area {
  background-color: #FFFFFF;
  padding: 20rpx;

  .share-content {
    position: relative;
    width: 100%;
    height: 400rpx;
    background-color: #f8f8f8;
    border-radius: 12rpx;
    overflow: hidden;

    image {
      width: 100%;
      height: auto;
      display: block;
    }

    .fullscreen-btn {
      position: absolute;
      right: 20rpx;
      top: 20rpx;
      width: 60rpx;
      height: 60rpx;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .share-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;

    .picker-content {
      display: flex;
      align-items: center;
      gap: 10rpx;
    }

    .file-name {
      font-size: 28rpx;
      color: #333;
    }

    .page-info {
      font-size: 24rpx;
      color: #999;
      margin: 0 10rpx;
    }
  }
}

.activity-area {
  flex: 1;

  .tabs {
    display: flex;
    background-color: #FFFFFF;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    .tab-item {
      flex: 1;
      text-align: center;
      font-size: 28rpx;
      color: #666;
      position: relative;

      &.active {
        color: #67C23A;
        font-weight: 500;

        &::after {
          content: '';
          position: absolute;
          bottom: -20rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #67C23A;
        }
      }
    }
  }

  .activity-list {
    padding: 20rpx;
    height: calc(100vh - 700rpx);
  }

  .activity-item {
    background-color: #FFFFFF;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;

    .activity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;

      .activity-title {
        font-size: 30rpx;
        font-weight: 500;
      }

      .activity-status {
        font-size: 26rpx;
        color: #909399;
      }
    }

    .activity-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .answer-text {
        font-size: 28rpx;
        color: #333;
      }

      .score {
        display: flex;
        align-items: center;
        gap: 6rpx;
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

// 全屏样式
.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #000;
  z-index: 999;

  image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

/* 讨论区域样式 */
.discussion-area {
  height: calc(100vh - 600rpx);
  background: #fff;
  padding: 20rpx;
}

.message-list {
  padding-bottom: 120rpx;
}

.message-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.sender {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.thumbs-up {
  margin-right: 10rpx;
}

.content {
  font-size: 28rpx;
}

/* 发送区域样式 */
.send-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: #fff;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #eee;
}

.message-input {
  flex: 1;
  height: 72rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.send-btn {
  width: 120rpx;
  height: 72rpx;
  background: #67C23A;
  color: #fff;
  border-radius: 36rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.send-btn:active {
  opacity: 0.8;
}

/* 抢答弹窗样式 */
.answer-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .answer-popup-content {
    width: 80%;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    text-align: center;

    .answer-title {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .answer-code {
      font-size: 32rpx;
      margin: 20rpx 0;
    }

    .answer-time {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 30rpx;
    }

    .answer-buttons {
      display: flex;
      justify-content: space-around;
      gap: 20rpx;

      button {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
      }

      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }

      .enter-btn {
        background-color: #67C23A;
        color: #fff;
      }
    }
  }
}
/* 添加签到弹框样式 */
.sign-in-popup {
  background-color: #fff;
  border-radius: 16rpx;
  width: 600rpx;
  padding: 40rpx;

  .popup-header {
    text-align: center;
    margin-bottom: 40rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .popup-content {
    margin-bottom: 40rpx;

    .sign-code-input {
      margin-bottom: 20rpx;

      .label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
        display: block;
      }

      .sign-code-field {
        width: 100%;
        height: 80rpx;
        border: 1px solid #dcdfe6;
        border-radius: 4rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }
    }

    .countdown {
      display: flex;
      align-items: center;

      .label {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
      }

      .value {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }

  .popup-footer {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;

    .confirm-btn,
    .cancel-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      font-size: 28rpx;
    }

    .confirm-btn {
      background-color: #67C23A;
      color: #fff;
    }

    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
  }
}

.sign-in-text,
.sign-in-duration {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

.detail-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;

  .label {
    font-size: 28rpx;
    color: #666;
    width: 160rpx;
  }

  .value {
    font-size: 28rpx;
    color: #333;

    &.success {
      color: #67C23A;
    }
  }
}

.activity-item {
  cursor: pointer;

  &:hover {
    background-color: #f5f5f5;
  }
}
</style>
